import PageTemplate from '@/components/common/PageTemplate'
import {getStartAct,insertWin,delFile,addDraft,getNextApprovePerson,
    getBpmPscActInfo,getWFConfigActivity, getWFConfigProcID} from '@/api/api.js'
import PersonSelect from '@/components/asc/PersonSelect'
import DeptSelect from '@/components/asc/DeptSelect'
import procApprove from '@/components/common/procApprove'
import fixedbutton from '@/components/common/fixedbutton'

import download from '@/components/common/download'
import PurProcessDemChangeEdit from '@/components/purchase/PurProcessDemChangeEdit'
import FileUploadCommon from '@/components/common/FileUploadCommon'
import { mapState, mapActions, mapGetters } from 'vuex'
import * as Constant from '@/utils/constant'
import { ALERT } from '@/utils/responseHandle'
import {COMMON} from '@/utils/commonUtil'
import {dateFtt} from '@/utils/datetime'
import _remove from 'lodash/remove'
import api_pur from '@/api/api_pur'
import store from '@/store'

export default {
    components:{
      PageTemplate,
        PersonSelect,
        DeptSelect,
        procApprove,
        fixedbutton,
        download,
        PurProcessDemChangeEdit,
        FileUploadCommon
    },
    data() {
        return {
            isStartAct: true, // 建单
            fileListDislogVisible: false, //
            fileUploadUrl:process.env.UPDOWN_ROOT,
            showCollapse2:"1",
            showCollapse:"1",
            hasIcon:false,
            loading:false,
            fileList:[],
            fileListDownLoad:[],
            showCollapse1:"1",
            flowDetails:{
                nextActOptions:[],
                approvePerson:[],
                approvePersonId:[],
                activityName:'010',
                isEnd:false,
                actParticipants:{},
                showBack: false
            },
            fileProps:[ //文件上传的属性
                {prop:'fileRealName',label:'文件名'},
                {prop:'createTime',label:'上传时间'},
            ],
            flow_access:{
                task_type:'',//任务类型
                mergeTask:'0',//合并任务
                slotCount:'1',//任务处理规则
                resign:'',//会签类型
                reselMan:'',//是否重选快速审批人
                act_name:'',//当前节点名称
                now_deal_act:'010',//当前节点
                deal_answer:'1',//同意 还是退回
                next_deal_act:'',//下一节点
                next_deal_name:[],//下一处理人 [pxmwrya]阮洋  多个
                deal_suggest:'',//审批意见
                copygive:"",//抄送人
                approveMan:'',//当前提交人 自己
                procInstId:'',//流程实例ID
                sn:'',//sn
                backAct:'',//退回节点  020
                backMan:'',//退回人
                procSetId:'',//流程集ID 兑奖流程 463
                fullName:'BMWS\\TestProcess',//流程全名
                procChName:'',//流程中文名
                procVerId:'',
                isEnd:false
            },
            win:{
              folio: '1',
              fileId: 'aa',
              fileName: '',
              filePath: '',
              originator: '', // 编制人
              reason: '', // 原因
              purchaseContractItemList: [] //
            },
            nextObj: {}
        }
    },
    created () {
      this.win.originator = this.user.userName
      this.purChangeProcessGet(this.$router.history.current.query.obj.formInstID);
      this.isStartAct = false;
      this.nextObj = this.$router.history.current.query.obj;
      this.flow_access.procInstId = this.nextObj.procInstID;
      this.flowDetails.showBack = this.nextObj.showBack;
      this.flowDetails.backAct = this.nextObj.backAct;
      this.flowDetails.backActName = this.nextObj.backActName;
      this.flowDetails.backManName = this.nextObj.backManName;
      this.flowDetails.backMan = this.nextObj.backMan;
      this.flow_access.backAct = this.nextObj.backAct[0];
      this.flow_access.backMan = this.nextObj.backMan[0];
      this.flow_access.backManName = this.nextObj.backManName[0];


      console.log("初始状态的flow_access",this.flow_access);
    },
    methods: {
        // 根据环节获取信息
        purChangeProcessGet (id) {
          api_pur.purChangeProcessGet({id, activityName: '010_需求人提交年度采购需求'}, result => {
            if (result.code === Constant.RT_SUCCESS) {
              this.win = result.data
              if (result.data.filePath) {
                this.fileList.push({
                  name: result.data.fileName,
                  url: result.data.filePath
                })
              }
            } else {
              // _this.$t('cm.tips')
              ALERT.error(result.msg)
            }
          })
        },
        //数据初始化
        initData:function(){
            this.flow_access.procChName = store.state.proc.procName ? store.state.proc.procName : '年度采购需求变更审批';
            this.flow_access.fullName = 'SWP-SU\\pur_demChange';
            this.flow_access.procSetId = store.state.proc.procSetId;
            this.flow_access.procVerId = store.state.proc.procId;
            //获取最新流程procId
            this.getWFConfigProc({fullName: this.flow_access.fullName});
        },
        getWFConfigProc(params){ // 获取最新流程procId
          let _this = this;
          getWFConfigProcID(params).then((result) => {
            if(result.status == "200" && result.data.code == "0"){
                let data = result.data.data || {}
                _this.flow_access.procSetId  = data.procSetID
                _this.getSomeInfo(data.procID);
            }else{
                _this.$alert(result.data.msg,_this.$t('cm.tips'));
            }
          }).catch((err) => {
              _this.$alert(err,_this.$t('cm.tips'));
          });
        },
        getSomeInfo(procVerId){
            //获取流程的开始节点、下一节点还有下一节点处理人
            let _this = this;
            let act_metadata_cur = null;
            if(this.nextObj.activityName == "020_队办经理审批") {
                act_metadata_cur = "020";
                this.flow_access.now_deal_act = "020";
            }
            if(this.nextObj.activityName == "030_计划协调员审批") {
              act_metadata_cur = "030";
              this.flow_access.now_deal_act = "030";
            }
            if(this.nextObj.activityName == "040_调试采购主管审批") {
              act_metadata_cur = "040";
              this.flow_access.now_deal_act = "040";
            }
            let data = {
              // act_id: this.nextObj.actOptions[0].actId,
              // act_metadata: this.nextObj.actOptions[0].actMetadata,
              // act_name: this.nextObj.actOptions[0].actName,
              // act_uuid:this.nextObj.actOptions[0].actUuid,
              // proc_id: this.nextObj.actOptions[0].procId,
              // task_act_type: this.nextObj.actOptions[0].taskActType,
              // task_process_rule: this.nextObj.actOptions[0].taskProcessRule,
              act_id: this.nextObj.activityID,
            //   act_metadata: this.nextObj.backAct[0], //这里不能这样判断，backAct不可能是当前环节的act_metadata
              act_metadata: act_metadata_cur,
              act_name: this.nextObj.activityName,
              proc_id: this.nextObj.procID
            }
            _this.flow_access.act_name = data.act_name;//当前环节名称
            _this.flowDetails.activityName = data.act_name;//用于页面显示
            _this.flow_access.staffNoBefore=this.nextObj.preActivitySender; //上一审批人
            _this.flow_access.procId = this.nextObj.procID;//提交需要
            _this.flow_access.actId = this.nextObj.activityID;//提交需要
            // _this.flowDetails.activityName = data.act_name;//用于页面显示
            //获取下一处理环节
            _this.getNextDealNode(data);
        },
        //保存草稿
        saveDraft:function(){
            let _this = this;
            //下一步处理人设置
            if(document.getElementById("appMan")!= null && document.getElementById("appMan").value != ""){
                this.flow_access.next_deal_name = document.getElementById("appMan").value.split(',');
            }
            //判断业务表数据  判断获奖表
            this.flow_access.isSaveDraft = "1";//说明是保存草稿
            this.$refs['win'].validate((valid)=>{
                if(valid){
                    if(this.checkValid()){
                        //设置关联文件
                        this.flow_access.fileList = this.fileListDownLoad;
                        // this.win.cudBonusProperty = this.win.cudBonusProperty.join(',');

                        let _this = this;
                        this.flow_access.win = this.win;

                        //调用保存草稿后台
                        addDraft(this.flow_access).then((result) => {
                            if(result.status == "200" && result.data.code == "0"){
                                _this.$router.push("/mydraft");
                            }else{
                                _this.$alert(result.data.msg,_this.$t('cm.tips'));
                            }
                        }).catch((err) => {
                            _this.$alert(err,_this.$t('cm.tips'));
                        });
                    }
                }
            });
        },
        // 提交流程
        saveProc () {
          if (this.isStartAct) {
            this.addProc()
          } else {
            this.purChangeProcessSubmit()
          }
        },
        //添加一个流程
        addProc:function(){
            //下一步处理人 设置
            if(document.getElementById("appMan")!= null && document.getElementById("appMan").value != ""){
                this.flow_access.next_deal_name = document.getElementById("appMan").value.split(',');
            }
            //判断获奖表
            this.$refs['win'].validate((valid)=>{
                if(valid){
                    if(this.flow_access.deal_answer == ""){
                        this.$alert("请选择处理结论!",this.$t('cm.tips'));
                        return ;
                    }
                    if(this.flow_access.next_deal_act == ""){
                        this.$alert("请选择下一环节!",this.$t('cm.tips'));
                        return ;
                    }
                    if(this.flow_access.next_deal_name == "" && this.flow_access.backMan ==""){
                        this.$alert("请选择下一步处理人22",this.$t('cm.tips'));
                        return ;
                    }
                    //设置任务类型、会签规则、会签类型、是否重选快速审批人 http://cudflow-d
                    let selNextAct = this.flowDetails.nextActOptions.find(n =>{
                        return (n.actMetadata == this.flow_access.next_deal_act);
                    })

                    this.flow_access.task_type = selNextAct.taskActType;
                    this.flow_access.mergeTask = selNextAct.isMergeTask;
                    this.flow_access.slotCount = selNextAct.taskProcessRule;
                    this.flow_access.resign = selNextAct.reSignType;
                    this.flow_access.reselMan = selNextAct.isReselFastDealer;

                    //设置关联文件
                    this.flow_access.fileList = this.fileListDownLoad;

                    // this.win.cudBonusProperty = this.win.cudBonusProperty.join(',');

                    let _this = this;
                    this.win.fileName = this.fileList.length > 0? this.fileList[0].name : null
                    this.win.filePath = this.fileList.length > 0? this.fileList[0].url : null
                    this.flow_access.win = this.win;
                    //存储数据
                    // insertWin(this.flow_access).then((result) => {
                    //     if(result.status == "200" && result.data.code=="0"){
                    //         _this.$alert("提交成功!",_this.$t('cm.tips'),{
                    //             callback:_ => {
                    //                 _this.$router.push("/already_done_task");
                    //             }
                    //         });
                    //     }else{
                    //         _this.$alert(result.data.msg,_this.$t('cm.tips'));
                    //     }
                    // }).catch((err) => {
                    //     _this.$alert(err,_this.$t('cm.tips'));
                    // });
                    api_pur.purChangeProcessSave(this.flow_access, result => {
                      if (result.code === Constant.RT_SUCCESS) {
                        ALERT.success(result.msg)
                        _this.$router.push(Constant.ROUTE_ALREADY_DONE_TASK.index);
                      } else {
                        ALERT.success(result.msg)
                      }
                    })
                }else{
                    return false;
                }
            })
        },
        // 审批流程
        purChangeProcessSubmit () {
          if(this.flow_access.deal_answer == ""){
            this.$alert("请选择处理结论!",this.$t('cm.tips'));
            return ;
          }
          if(this.flow_access.next_deal_act == ""){
              this.$alert("请选择下一环节!",this.$t('cm.tips'));
              return ;
          }
          console.log(this.flow_access);
          if(this.flow_access.participantSelectRestlt) {
              let value = [];
              let parts = this.flow_access.participantSelectRestlt.split(",");
              for(let i = 0; i < parts.length; i++){
                  value.push(parts[i]);
              }
              this.flow_access.next_deal_name = value;
          }
          console.log(this.flow_access);
          if(this.flow_access.next_deal_name == "" && this.flow_access.backMan ==""){
              this.$alert("请选择下一步处理人。",this.$t('cm.tips'));
              return ;
          }
          //设置任务类型、会签规则、会签类型、是否重选快速审批人 http://cudflow-d
          let selNextAct = this.flowDetails.nextActOptions.find(n =>{
              // return (n.actMetadata == this.flow_access.next_deal_act);
              return true
          })
          this.flow_access.task_type = selNextAct.taskActType;
          this.flow_access.mergeTask = selNextAct.isMergeTask;
          this.flow_access.slotCount = selNextAct.taskProcessRule;
          this.flow_access.resign = selNextAct.reSignType;
          this.flow_access.reselMan = selNextAct.isReselFastDealer;

          this.flow_access.auditNote = this.flow_access.deal_suggest;
          this.flow_access.formInstID = this.nextObj.formInstID;
          this.flow_access.procInstId = this.nextObj.procInstID;
          this.flow_access.sn = this.nextObj.sn;
          //设置关联文件
          this.flow_access.fileList = this.fileListDownLoad;
          let _this = this;
          api_pur.purChangeProcessSubmit(this.flow_access, result => {
            if (result.code === Constant.RT_SUCCESS) {
              ALERT.success(result.msg)
              _this.$router.push(Constant.ROUTE_ALREADY_DONE_TASK.index);
            } else {
              ALERT.success(result.msg)
            }
          })
        },
        getNextDealNode:function(data){//获取下一节点 通过 下一步点处理人接口
            let _this = this;
            let params = {
                actId: data.act_id,
                procInstId: _this.nextObj.procInstID,
                procId: data.proc_id,
                node: data.act_metadata,
            }
            console.log(params);
            getNextApprovePerson(params).then((result) => {
                if(result.status == "200" && result.data.code == "0"){
                    let data = result.data.data.data;
                    this.getNextNodeInfo(data);
                }else{
                    _this.$alert(result.data.msg,_this.$t('cm.tips'));
                }
            }).catch((err) => {
                _this.$alert(err,_this.$t('cm.tips'));
            });
        },
        //获取下一节点详情
        getNextNodeInfo:function(data){
            console.log(data)
            //获取流程配置中的流程节点信息  可以存储在store中
            let _this = this;
            let params = {
                fullName: this.flow_access.fullName,
                // procSetId: this.flow_access.procSetId
                //带procSetId请求接口发现返回了流程所有版本的环节
                procSetId: ""
            };
            getWFConfigActivity(params).then((result) => {
                if(result.status == "200" && result.data.code == "0"){
                    //存在多个下一环节的情况
                    for(const metadata in data){
                        let d = result.data.data.data;
                        for(let i = 0; i < d.length; i++){
                            if(d[i].actMetaData == metadata){
                                _this.flowDetails.actParticipants[metadata] = data[metadata];
                                // _this.unifyUser(data[metadata]);//处理下一步处理人(此处不应该直接对处理人进行处理，因为环节尚未选定)
                                _this.getNextNodeDetails(d[i]);

                                //设置 下一环节和下一步处理人的参数 同时获取下一环节节点详情
                                // flowDetails:{
                                //     nextActOptions:[],
                                //     approvePerson:[],
                                //     approvePersonId:[],
                                // }

                            }
                        }
                    }
                }else{
                    _this.$alert(result.data.msg,_this.$t('cm.tips'));
                }
            }).catch((err) => {
                _this.$alert(err,_this.$t('cm.tips'));
            });
        },
        //获取下一节点详细信息
        getNextNodeDetails(arr){
            let _this = this;
            getBpmPscActInfo({actId:arr.actID}).then((result) => {
                if(result.status == "200" && result.data.code == "0"){
                    let data = result.data.data.data;
                    //获取下一步点处理人
                    if(data) {
                        _this.flowDetails.nextActOptions.push(data);
                    }

                }else{
                    _this.$alert(result.data.msg,_this.$t('cm.tips'));
                }
            }).catch((err) => {
                _this.$alert(err,_this.$t('cm.tips'));
            });

        },
        //统一用户格式
        unifyUser:function(users){
            for(let i = 0; i < users.length; i++){
                if(typeof(users[i].item_principal_desc) != "undefined" && typeof(users[i].item_principal_desc) != null){
                    this.flowDetails.approvePerson.push("["+users[i].item_principal+"]"+users[i].item_principal_desc);
                    this.flowDetails.approvePersonId.push(users[i].item_principal);
                }
            }
        },
        //上传文件时的回调
        upfileBack:function(response, file, fileList){
            this.loading = false;
            if(response.code == "0"){
                this.fileListDownLoad.push(response.data);
            }else{
                this.$alert(response.msg,this.$t('cm.tips'));
            }
        },
        //上传文件之前的处理
        beforeUpload:function(file){
            //在这里进行上传文件的设置
            let type = file.name.substring(file.name.lastIndexOf('.')+1);
            const limitSize = file.size / 1024 /1024 < 10; //文件大小限制
            if(!limitSize){
                this.$alert("上传文件大小不能超过10M",this.$t('cm.tips'));
            }
            return limitSize;
        },
        loadingFile:function(){
            this.loading = true;
        },
        uplofileError:function(){
            this.loading = false;
        },
        //删除文件
        delFiles:function(row){
            let _this = this;
            delFile({fileId:row.fileId}).then((result) => {
                if(result.status == "200" && result.data.code == "0"){
                    _this.fileListDownLoad.splice(_this.fileListDownLoad.findIndex(item => item.fileId===row.fileId),1);
                }else{
                    _this.$alert(result.data.msg,_this.$t('cm.tips'));
                }
            }).catch((err) => {
                _this.$alert(err,_this.$t('cm.tips'));
            });
        },
        checkValid(){
            if(this.flow_access.deal_answer == ""){
                this.$alert("请选择处理结论!",this.$t('cm.tips'));
                return false;
            }else if(this.flow_access.next_deal_act == ""){
                this.$alert("请选择下一环节!",this.$t('cm.tips'));
                return false;
            }else if(this.flow_access.next_deal_name == "" && this.flow_access.backMan =="")
            {
                this.$alert("请选择下一步处理人",this.$t('cm.tips'));
                return false;
            }else{
                return true;
            }
        },
        addFileListDislog () {
          this.fileListDislogVisible = true
        },
        closeFileListDislog () {
          this.fileListDislogVisible = false
        },
        addFileList (data) {
          this.win.purchaseContractItemList.push(data)
          this.fileListDislogVisible = false
        },
        triggerDelListBtn (data) {
          _remove(this.win.purchaseContractItemList, (item) => {
            return data.id === item.id
          })
          this.win.purchaseContractItemList = JSON.parse(JSON.stringify(this.win.purchaseContractItemList))
        },
        uploadSuccess (res, fileKey) {
          if (res.data && res.data[0]) {
            let file = {name: res.data[0].fileName, url: res.data[0].url, fileId: res.data[0].fileId}
            this.fileList.push(file)
          }
        },
        uploadRemove (fileList, fileKey) {
          let resList = fileList.map(item => {
            return {
              name: item.name,
              url: item.url,
              fileId: item.fileId
            }
          })
          this.fileList = resList
        },
        formatTableText (row, column, cellValue, index) {
          var fmtValue = null
          if (column.property=== 'requiredArrivalTime') {
            fmtValue = dateFtt('yyyy-MM-dd', row.requiredArrivalTime)
          } else if (column.property=== 'plannedCompletionTime') {
            fmtValue = dateFtt('yyyy-MM-dd', row.plannedCompletionTime)
          }  else if (column.property=== 'currency') {
            fmtValue = this.currencyMap[row.currency]
          }
          return fmtValue !== null && fmtValue !== undefined ? fmtValue : cellValue
        }
    },
    mounted() {
        //初始化数据 应该获取兑奖流程的信息
        this.initData();
    },
    computed: {
        ...mapState({
          tableHeaderBGC: state => state.common.tableHeaderBGC,
          user: state => state.user.user
        }),
        ...mapGetters({
          currencyMap: 'dict/currencyMap'
        }),
        winRules:function(){
            return {
            }
        }
    },
}
